import http from './http'

// 增强AI相关类型定义
export interface ChatRequest {
  query: string
  context?: string
}

export interface EnhancedAIResponse {
  originalQuery: string
  detectedIntent: QueryIntent
  confidence: number
  enhancedPrompt: string
  aiResponse: string
  responseTimeMs: number
  hasCodePattern: boolean
  suggestedTopics: string[]
  learningResources: string[]
}

export interface UserLearningStats {
  totalQuestions: number
  programmingQuestions: number
  skillLevel: string
  currentLanguage: string
  recentTopics: string[]
  weakAreas: string[]
  strongAreas: string[]
  lastActiveAt: string
}

export interface UserPreferencesRequest {
  currentLanguage?: string
  learningGoals?: string
}

export interface IntentAnalysis {
  intent: QueryIntent
  confidence: number
  keywords: string[]
  hasCodePattern: boolean
  complexity: string
}

export type QueryIntent = 
  | 'PROGRAMMING' 
  | 'CODE_DEBUG' 
  | 'CODE_REVIEW' 
  | 'CONCEPT_EXPLANATION' 
  | 'PROJECT_HELP' 
  | 'LEARNING' 
  | 'GENERAL'

export type SkillLevel = 'BEGINNER' | 'INTERMEDIATE' | 'ADVANCED' | 'EXPERT'

// 增强AI API
export const enhancedAIApi = {
  /**
   * 智能问答
   */
  chat(request: ChatRequest): Promise<EnhancedAIResponse> {
    return http.post('/v1/ai/enhanced/chat', request)
  },

  /**
   * 获取用户学习统计
   */
  getUserStats(): Promise<UserLearningStats> {
    return http.get('/v1/ai/enhanced/user-stats')
  },

  /**
   * 更新用户学习偏好
   */
  updateUserPreferences(request: UserPreferencesRequest): Promise<string> {
    return http.put('/v1/ai/enhanced/user-preferences', request)
  }
}

// 工具函数
export const aiUtils = {
  /**
   * 获取意图的显示名称
   */
  getIntentDisplayName(intent: QueryIntent): string {
    const intentNames: Record<QueryIntent, string> = {
      'PROGRAMMING': '编程相关',
      'CODE_DEBUG': '代码调试',
      'CODE_REVIEW': '代码审查',
      'CONCEPT_EXPLANATION': '概念解释',
      'PROJECT_HELP': '项目帮助',
      'LEARNING': '学习相关',
      'GENERAL': '通用问题'
    }
    return intentNames[intent] || '未知'
  },

  /**
   * 获取技能水平的显示名称
   */
  getSkillLevelDisplayName(level: string): string {
    const levelNames: Record<string, string> = {
      'BEGINNER': '初学者',
      'INTERMEDIATE': '中级',
      'ADVANCED': '高级',
      'EXPERT': '专家'
    }
    return levelNames[level] || level
  },

  /**
   * 获取意图对应的图标
   */
  getIntentIcon(intent: QueryIntent): string {
    const intentIcons: Record<QueryIntent, string> = {
      'PROGRAMMING': '💻',
      'CODE_DEBUG': '🐛',
      'CODE_REVIEW': '📋',
      'CONCEPT_EXPLANATION': '💡',
      'PROJECT_HELP': '🚀',
      'LEARNING': '📚',
      'GENERAL': '❓'
    }
    return intentIcons[intent] || '❓'
  },

  /**
   * 获取置信度颜色
   */
  getConfidenceColor(confidence: number): string {
    if (confidence >= 0.8) return '#52c41a' // 绿色 - 高置信度
    if (confidence >= 0.6) return '#faad14' // 橙色 - 中等置信度
    return '#ff4d4f' // 红色 - 低置信度
  },

  /**
   * 格式化响应时间
   */
  formatResponseTime(timeMs: number): string {
    if (timeMs < 1000) return `${timeMs}ms`
    return `${(timeMs / 1000).toFixed(1)}s`
  },

  /**
   * 检测文本中的代码块
   */
  hasCodeBlock(text: string): boolean {
    return /```[\s\S]*?```/.test(text) || /`[^`]+`/.test(text)
  },

  /**
   * 提取代码块
   */
  extractCodeBlocks(text: string): Array<{language: string, code: string}> {
    const codeBlocks: Array<{language: string, code: string}> = []
    const regex = /```(\w+)?\n([\s\S]*?)```/g
    let match

    while ((match = regex.exec(text)) !== null) {
      codeBlocks.push({
        language: match[1] || 'text',
        code: match[2].trim()
      })
    }

    return codeBlocks
  },

  /**
   * 高亮关键词
   */
  highlightKeywords(text: string, keywords: string[]): string {
    let highlightedText = text
    keywords.forEach(keyword => {
      const regex = new RegExp(`\\b${keyword}\\b`, 'gi')
      highlightedText = highlightedText.replace(regex, `<mark>$&</mark>`)
    })
    return highlightedText
  }
}
